package cn.com.connext.scrm.utils;

import com.connext.common.exception.ErrorCode;
import com.connext.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;

/**
 * FIXME: 临时测试类
 */
public class DBUtil {

    private static final Logger log = LoggerFactory.getLogger(DBUtil.class);

    private DBUtil() {
    }

    /**
     * 根据表名称创建一张表
     *
     * @param tableName
     */
    public static int createTable(JdbcTemplate jt, String tableName, Object obj) {
        StringBuilder sb = new StringBuilder();

        sb.append("CREATE TABLE `" + tableName + "` (");
        sb.append(" `id` int(11) NOT NULL AUTO_INCREMENT,");
        Map<String, String> map = ObjectUtil.getProperty(obj);
        Set<String> set = map.keySet();
        for (String key : set) {
            sb.append("`" + key + "` varchar(255) DEFAULT '',");
        }
        sb.append(" `tableName` varchar(255) DEFAULT '',");
        sb.append(" PRIMARY KEY (`id`)");
        sb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        try {
            jt.update(sb.toString());
            return 1;
        } catch (Exception e) {
            log.error("createTable error : ", e);
        }
        return 0;
    }

    /**
     * 查询数据库是否有某表
     *
     * @param jt
     * @param tableName
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static boolean getAllTableName(JdbcTemplate jt, String tableName) {
        Connection conn = null;
        try {
            conn = jt.getDataSource().getConnection();
        } catch (SQLException e) {
            log.error("getAllTableName error : ", e);
            throw new ServiceException(ErrorCode.ERROR_UNKNOW, e);
        }
        ResultSet tabs = null;
        try {
            DatabaseMetaData dbMetaData = conn.getMetaData();
            String[] types = {"TABLE"};
            tabs = dbMetaData.getTables(null, null, tableName, types);
            if (tabs.next()) {
                return true;
            }
        } catch (Exception e) {
            log.error("getAllTableName error : ", e);
        } finally {
            if(tabs != null){
                try {
                    tabs.close();
                } catch (SQLException e) {
                    log.error("getAllTableName error : ", e);
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("getAllTableName error : ", e);
                }
            }
        }
        return false;
    }
}
